# app相关操作
import os
import requests

from Lib.zcm.assistant.FwConfigUtils import case_path

DEFAULT_DOWNLOAD_PACKAGE = os.path.join(case_path, "apk_package")


# 下载apk
def download_apk(download_url, apk_name=None):
    if not download_url:
        raise Exception("invalid parameter: download_url cannot be empty!")
    if download_url.endswith("/"):
        download_url = download_url[:-1]
    rsp = requests.get(download_url)
    if not os.path.exists(DEFAULT_DOWNLOAD_PACKAGE):
        os.mkdir(DEFAULT_DOWNLOAD_PACKAGE)
    if not apk_name:
        download_file_name = download_url.split("/")[-1]
        apk_name = os.path.join(DEFAULT_DOWNLOAD_PACKAGE, download_file_name)
    else:
        # 以"/"开头，认为是绝对路径，否则是相对路径，默认是存在/home/seluser/testproject/Case/apk_package
        if not apk_name.startswith("/"):
            apk_name = os.path.join(DEFAULT_DOWNLOAD_PACKAGE, apk_name)
    if 200 <= rsp.status_code < 300:
        with open(apk_name, "wb") as f:
            f.write(rsp.content)
        return apk_name
    else:
        raise Exception("download apk failed! {}".format(rsp.text))


# 安装apk
def install_apk(apk_name):
    # 以"/"开头，认为是绝对路径，否则是相对路径，默认是存在/home/seluser/testproject/Case/apk_package
    if not apk_name.startswith("/"):
        apk_name = os.path.join(DEFAULT_DOWNLOAD_PACKAGE, apk_name)
    install_code = os.system("adb install {}".format(apk_name))
    if install_code != 0:
        raise Exception("install pak failed!")